package com.ruoyi.project.system.commodity.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.project.system.commodity.controller.utils.PageMsg;
import com.ruoyi.project.system.commodity.domain.*;
import com.ruoyi.project.system.commodity.servuce.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@Controller
@RequestMapping("/api/commodity")
@ResponseBody
public class CommodityApiController {

    @Autowired
    BrandService brandService;

    @Autowired
    SpecsKeyService specsKeyService;

    @Autowired
    SpecsValueService specsValueService;

    @Autowired
    SystematicsService systematicsService;

    @Autowired
    SpecsGroupService specsGroupService;

    @Autowired
    GoodsInfoService goodsInfoService;

    @Autowired
    GoodsSkuService goodsSkuService;

    @Autowired
    GoodsSkuSpecsService goodsSkuSpecsService;

    @Autowired
    GoodsCarouselService goodsCarouselService;



//    TODO 添加商品

    @PostMapping("/addGoods")
    @Transactional
    public Map<String,Object> addGoods(@RequestBody Map<String,Object> reMap){
        String goodsInfoJson = JSON.toJSONString(reMap.get("goodsInfo"));
        GoodsInfo goodsInfo = (GoodsInfo) JSONObject.toBean(JSONObject.fromObject(goodsInfoJson),GoodsInfo.class);
//         添加信息进入商品基本信息表 返回插入的id
        goodsInfoService.insertGoodsInfo(goodsInfo);
        int goodsInfoId = goodsInfo.getGoodsInfoId();

        JSONArray goodsSkusJson = JSONArray.fromObject(JSON.toJSONString(reMap.get("goodsSkus")));
        List<GoodsSku> goodsSkus = (List<GoodsSku>) JSONArray.toCollection(goodsSkusJson,GoodsSku.class);
        for (GoodsSku goodsSku : goodsSkus) {

            System.out.println(goodsSku);
            addGoodsSkuUtil(goodsSku,goodsInfoId);
        }

        JSONArray carouselUrlsJson = JSONArray.fromObject(JSON.toJSONString(reMap.get("carouselUrl")));
        List<String> carouselUrls = (List<String>) JSONArray.toCollection(carouselUrlsJson,String.class);
        for (String carouselUrl : carouselUrls) {
            GoodsCarousel goodsCarousel = new GoodsCarousel(carouselUrl,goodsInfoId);
            goodsCarouselService.insertCarousel(goodsCarousel);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

//    TODO 下架商品
    @GetMapping("/OffShelfGoods/{id}")
    public Map<String, Object> OffShelfGoods(@PathVariable("id") int id){
        goodsInfoService.offShelfGoodsById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

    @GetMapping("/putShelfGoods/{id}")
    public Map<String, Object> putShelfGoods(@PathVariable("id") int id){
        goodsInfoService.putShelfGoods(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }


//    TODO 编辑商品
    @PostMapping("/updateGoods")
    @Transactional
    public Map<String,Object> updateGoods(@RequestBody Map<String,Object> reMap){
        String goodsInfoJson = JSON.toJSONString(reMap.get("goodsInfo"));
        GoodsInfo goodsInfo = (GoodsInfo) JSONObject.toBean(JSONObject.fromObject(goodsInfoJson),GoodsInfo.class);
        goodsInfoService.updateGoodsInfo(goodsInfo);

        JSONArray goodsSkusJson = JSONArray.fromObject(JSON.toJSONString(reMap.get("goodsSkus")));
        List<GoodsSku> goodsSkus = (List<GoodsSku>) JSONArray.toCollection(goodsSkusJson,GoodsSku.class);
        for (GoodsSku goodsSku : goodsSkus) {
            goodsSku.setGoodsId(goodsInfo.getGoodsInfoId());
            goodsSkuService.updateSku(goodsSku);
            int skuId = goodsSku.getSkuId();
            String skuCode = goodsSku.getSkuCode();
            String[] specs = skuCode.split("#");
            for (String spec : specs) {
                String key = spec.split("-")[0];
                String value = spec.split("-")[1];
                System.out.println(key+":"+value);
                GoodsSkuSpecs goodsSkuSpecs = new GoodsSkuSpecs(Integer.parseInt(key),Integer.parseInt(value),skuId,goodsInfo.getGoodsInfoId());
                System.out.println(goodsSkuSpecs);
                goodsSkuSpecsService.updateSkuSpecs(goodsSkuSpecs);
            }
        }

        JSONArray carouselUrlsJson = JSONArray.fromObject(JSON.toJSONString(reMap.get("carouselUrl")));
        List<String> carouselUrls = (List<String>) JSONArray.toCollection(carouselUrlsJson,String.class);
        for (String carouselUrl : carouselUrls) {
            GoodsCarousel goodsCarousel = new GoodsCarousel(carouselUrl,goodsInfo.getGoodsInfoId());
            goodsCarouselService.updateCarousel(goodsCarousel);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

    @PostMapping("/addGoodsSku")
    public  Map<String,Object> addGoodsSku(@RequestBody Map<String,Object> reMap){
        String goodsSkuJson = JSON.toJSONString(reMap.get("goodsSku"));
        GoodsSku goodsSku = (GoodsSku) JSONObject.toBean(JSONObject.fromObject(goodsSkuJson),GoodsSku.class);
        System.out.println((Integer) reMap.get("goodsId"));
        System.out.println(goodsSku);
        addGoodsSkuUtil(goodsSku, (Integer) reMap.get("goodsId"));
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
}

    public void addGoodsSkuUtil(GoodsSku goodsSku,int goodsInfoId){
        goodsSku.setGoodsId(goodsInfoId);
        goodsSkuService.insertSku(goodsSku);
        int skuId = goodsSku.getSkuId();
        System.out.println(skuId);
        String skuCode = goodsSku.getSkuCode();
        String[] specs = skuCode.split("#");
        for (String spec : specs) {
            String key = spec.split("-")[0];
            String value = spec.split("-")[1];
            System.out.println(key+":"+value);
            GoodsSkuSpecs goodsSkuSpecs = new GoodsSkuSpecs(Integer.parseInt(key),Integer.parseInt(value),skuId,goodsInfoId);
            System.out.println(goodsSkuSpecs);
            goodsSkuSpecsService.insertSkuSpecs(goodsSkuSpecs);
        }
    }

//    TODO 查询商品
    @GetMapping("/querySpu")
    public Map<String, Object> querySpu(@Param("start") int page, @Param("pageSize") int pageSize){
        int count = goodsInfoService.querySpuCount();
        int start = (page-1) * pageSize;
        int end = (page-1) * pageSize + pageSize;

        List<GoodsInfo> goodsInfos = goodsInfoService.querySpu(start,pageSize);
        Map<String, Object> msgMap = PageMsg.getMsgMap(count, end, page,pageSize);
        msgMap.put("data",goodsInfos);
        return msgMap;
    }

    @GetMapping("/queryPath/{path}")
    public Map<String, Object> queryPath(@PathVariable("path") String path){
        List<String> goodsInfos = goodsInfoService.queryPath(path);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        map.put("data",goodsInfos);
        return map;
    }

    @GetMapping("/querySpuByName")
    public Map<String, Object> querySpuByName(GoodsInfo goodsInfo){
        List<GoodsInfo> goodsInfos = goodsInfoService.querySpuByName(goodsInfo);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        map.put("data",goodsInfos);
        return map;
    }

//    TODO 删除商品
    @GetMapping("/deleteSpu/{id}")
    public Map<String, Object> deleteSpu(@PathVariable("id") int id){
        goodsInfoService.deleteSpu(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }



//    TODO 新增分类
    @PostMapping("/addSystematics")
    @Transactional
    public Map<String, Object> addSystematics(@RequestBody Map<String, Object> reMap){
        String systematicsJson = JSON.toJSONString(reMap.get("systematics"));
        Systematics systematics = (Systematics) JSONObject.toBean(JSONObject.fromObject(systematicsJson), Systematics.class);
        systematicsService.insertSystematics(systematics);
        int systematicsId = systematics.getSystematicsId();
        JSONArray jsonArray = JSONArray.fromObject(JSON.toJSONString(reMap.get("specsId")));
        List<Integer> specsKeyIds = (List<Integer>) JSONArray.toCollection(jsonArray,Integer.class);
        for (Integer specsKeyId : specsKeyIds) {
            SpecsGroup specsGroup = new SpecsGroup(specsKeyId,systematicsId);
            specsGroupService.insertSpecsGroup(specsGroup);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }


//    TODO 编辑分类
    @GetMapping("/updateStatusOpenById/{id}")
    public  Map<String, Object> updateStatusOpenById(@PathVariable("id") int id){
        Systematics systematics = systematicsService.querySystematicsById(id);
        systematicsService.updateStatusOpenById(systematics);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

    @GetMapping("/updateStatusCloseById/{id}")
    public  Map<String, Object> updateStatusCloseById(@PathVariable("id") int id){
        Systematics systematics = systematicsService.querySystematicsById(id);
        systematicsService.updateStatusCloseById(systematics);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

    @PostMapping("/updateSystematics")
    public  Map<String, Object> updateSystematics(@RequestBody Map<String, Object> reMap){
        String systematicsJson = JSON.toJSONString(reMap.get("systematics"));
        Systematics systematics = (Systematics) JSONObject.toBean(JSONObject.fromObject(systematicsJson), Systematics.class);
        int systematicsId = systematics.getSystematicsId();
        systematicsService.updateSystematics(systematics);
        JSONArray jsonArray = JSONArray.fromObject(JSON.toJSONString(reMap.get("specsId")));
        List<Integer> specsKeyIds = (List<Integer>) JSONArray.toCollection(jsonArray,Integer.class);
        for (Integer specsKeyId : specsKeyIds) {
            SpecsGroup specsGroup = new SpecsGroup(specsKeyId,systematicsId);
            specsGroupService.updateSpecsGroup(specsGroup);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }




//    TODO 查询分类
    @GetMapping("/querySystematics")
    public Map<String, Object> querySystematics(){
//        List<Systematics> systematics = systematicsService.querySystematics();
        List<SystematicsFirst> systematicsFirsts = systematicsService.queryFirstSystematics();
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        map.put("data",systematicsFirsts);
        return map;
    }

    @GetMapping("/querySysChildById/{id}")
    public  Map<String, Object> querySysChildById(@PathVariable("id") int id){
        List<Systematics> systematics = systematicsService.querySysChildById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        map.put("data",systematics);
        return map;
    }

    @GetMapping("/queryFirstSys")
    public  Map<String, Object> queryFirstSysById(@Param("start") int page, @Param("pageSize") int pageSize){
        int count = systematicsService.querySysCount();
        int start = (page-1) * pageSize;
        int end = (page-1) * pageSize + pageSize;
        List<Systematics> systematics = systematicsService.queryFirstSys(start,pageSize);
        Map<String, Object> msgMap = PageMsg.getMsgMap(count, end, page,pageSize);
        msgMap.put("data",systematics);
        return msgMap;
    }



//    TODO 删除分类

    @GetMapping("/deleteSystematics/{id}")
    public Map<String, Object> deleteSystematicsById(@PathVariable("id") int id){
        Systematics systematics = systematicsService.querySystematicsById(id);
        System.out.println(systematics);
        systematicsService.deleteSystematicsById(systematics);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

//    TODO 新增规格
    @PostMapping("/addSpecs")
    @Transactional
    public Map<String, Object> addSpecs(@RequestBody Map<String,Object> reMap){
        String specsKeyJson = JSON.toJSONString(reMap.get("specsKey"));
        SpecsKey specsKeyBen = (SpecsKey) JSONObject.toBean(JSONObject.fromObject(specsKeyJson),SpecsKey.class);
        specsKeyService.insertSpecsKey(specsKeyBen);
        int keyId = specsKeyBen.getKeyId();
        String valuesJson = JSON.toJSONString(reMap.get("values"));
        JSONArray jsonArray = JSONArray.fromObject(valuesJson);
        List<String> values = (List<String>) JSONArray.toCollection(jsonArray,String.class);
        for (String value : values) {
            SpecsValue specsValue = new SpecsValue(value,keyId);
            specsValueService.insertSpecsValue(specsValue);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }


//    TODO 编辑规格
    @PostMapping("/updateSpecs")
    @Transactional
    public Map<String, Object> updateSpecs(@RequestBody Map<String,Object> reMap){
        String specsKeyJson = JSON.toJSONString(reMap.get("specsKey"));
        SpecsKey specsKeyBen = (SpecsKey) JSONObject.toBean(JSONObject.fromObject(specsKeyJson),SpecsKey.class);
        specsKeyService.updateSpecsKeyById(specsKeyBen);
        String specsValuesJson = JSON.toJSONString(reMap.get("specsValues"));
        JSONArray jsonArray = JSONArray.fromObject(specsValuesJson);
        List<SpecsValue> SpecsValues = (List<SpecsValue>) JSONArray.toCollection(jsonArray,SpecsValue.class);
        for (SpecsValue specsValue: SpecsValues) {
            specsValueService.updateSpecsValueById(specsValue);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }


//    TODO 查询规格
    @GetMapping("/querySpecsPage")
    public Map<String, Object> querySpecsPage(int page, int pageSize){
        int count = specsKeyService.querySpecsCount();
        int start = (page-1) * pageSize;
        int end = (page-1) * pageSize + pageSize;
        List<SpecsKey> specs = specsKeyService.querySpecsPage(start,pageSize);
        Map<String, Object> msgMap = PageMsg.getMsgMap(count, end, page,pageSize);
        msgMap.put("data",specs);
        return msgMap;
    }

    @GetMapping("/querySpecsByName/{name}")
    public Map<String, Object> querySpecsByName(@PathVariable("name") String name){
        List<SpecsKey> specsKeys = specsKeyService.querySpecsByName(name);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        map.put("data",specsKeys);
        return map;
    }

//    TODO 删除规格
    @GetMapping("/deleteSpecs/{keyId}")
    public Map<String, Object> deleteSpecsById(@PathVariable("keyId") int keyId){
        specsKeyService.deleteSpecsById(keyId);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }



//    TODO 新增品牌

    /**
     *
     * @param brand 品牌实体
     * @return  成功消息
     */
    @RequestMapping(value = "/addBrand",method = RequestMethod.POST)
    public Map<String, Object> addBrand(Brand brand){
        brandService.insertBrand(brand);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","success");
        return map;
    }

//    TODO 编辑品牌
    @PostMapping("/updateBrand")
    public Map<String, Object> updateBrandById(Brand brand){
        System.out.println(brand);
        brandService.updateBrandById(brand);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","update brand success");
        return map;
    }


//    TODO 查询品牌
    @RequestMapping("/queryBrands")
    public Map<String, Object> queryBrands(Brand brand){
        List<Brand> list = brandService.queryBrands();
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","insert success");
        map.put("data",list);
        return map;
    }

//    TODO 分页查询品牌
    @RequestMapping("/queryBrandsPages")
    public Map<String, Object> queryBrandsPages(@RequestParam int page, @RequestParam int pageSize){
        int count = brandService.queryBrandsCount();

        int start = (page-1) * pageSize;
        int end = (page-1) * pageSize + pageSize;
        List<Brand> list = brandService.queryBrandsPages(start,pageSize);
        Map<String, Object> msgMap = PageMsg.getMsgMap(count, end, page,pageSize);
        msgMap.put("data",list);
        return msgMap;
    }


    /**
     *
     * @param name 品牌名称
     * @param status 品牌在线状态
     * @return 符合条件的品牌
     */
    @RequestMapping("/queryBrandsByName")
    public Map<String, Object> queryBrandsByName(@Param("name") String name,@Param("status") int status){
        List<Brand> list = brandService.queryBrandsByName(name, status);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","query success");
        map.put("data",list);
        return map;
    }

//    TODO 删除品牌
    @GetMapping("/delete/{id}")
    public Map<String, Object> deleteBrand(@PathVariable("id") int id){

        brandService.deleteBrandById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","delete success");
        return map;
    }

    @PostMapping("/batchDelete")
    public Map<String, Object> batchDeleteBrand(@Param("list") Integer[] list){
        int n = 0;
        for (int id : list) {
            System.out.println(id);
            brandService.deleteBrandById(id);
            n ++;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","delete "+ n +"line");
        return map;
    }

//    TODO 禁用品牌
    @GetMapping("/disable/{id}")
    public Map<String, Object> disableBrand(@PathVariable("id") int id){

        brandService.disableBrandById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","disable brand success");
        return map;
    }

    //    TODO 启用品牌
    @GetMapping("/enable/{id}")
    public Map<String, Object> enableBrand(@PathVariable("id") int id){
        brandService.enableBrandById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg","enable brand success");
        return map;
    }
}
